import React, { Component, Fragment } from 'react';
import { Row, Col, Card, message, Button, Radio, Tag, Spin, Table, Modal, Popconfirm, Form, Input } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './success.less';
import Column from 'antd/lib/table/Column';
const QRCode = require('qrcode.react');
const RadioButton = Radio.Button;
function jiequ(arr,n) {
        var num = n;//一个数组里面的元素个数
       // var arr = [1,2,3,4,5,6,7,8,9,10];
        if(arr&&arr.length){
          var Arr = new Array(Math.ceil(arr.length/num));
          for(var i = 0; i<Arr.length;i++){
          Arr[i] = new Array();
          for(var j = 0; j<num; j++){
          Arr[i][j] = '';
          }
          }
          for(var i = 0; i<arr.length;i++){
            Arr[parseInt(i/num)][i%num] = arr[i];
          }
          return Arr
        }
        return []

}
@connect(({ xcxauth, loading }) => ({
  xcxauth,
  authInfo: xcxauth.authInfo,
}))
@Form.create()
class AuthSuccess extends Component {
  state={
    isAuth:true,
    reauthorizeVisible:false,
    lookVisible:false,
    addVisible:false,
    loading:true,
    code:0,
    bzLength:0,
    appIdList:[],
    wxaCode:'',
    xcxCodeModal:false,
    reloadLoading:false
  }
  componentWillMount() {
    window.Isoption = false;
    const { dispatch } = this.props;
    dispatch({
      type: `xcxauth/GetAuthStatus`,
      callback: {
          success: (res) => {
            if(res.Code===0){
              this.getAuthInfo();
              this.setState({
                isAuth:true,
              })
            }else{
              this.setState({
                isAuth:false,
                code:res.Code
              })
            }

          }
      }
    });

  }
  componentDidMount() {
    window.Isoption = true;
  }

  getAuthInfo =() =>{
    const { dispatch } = this.props;
    let that=this;
    dispatch({
      type: 'xcxauth/GetAuthInfo',
      callback: {
        success: res =>{
          that.setState({
            loading:false,
            wxaCode:res.Data.WxaCodePath
          })
        }
      }
    });
  }

  goAuth = () => {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'xcxauth/GetPreAuthUrl',
      //type:'xcxauth/GoToWeixin',
      callback: {
        success: res => {
          // dispatch({
          //   type: 'xcxauth/GoToWeixin',
          //   payload: {
          //     MpUrl: res.Data.MpUrl,
          //     NotifyUrl: res.Data.NotifyUrl,
          //   },
          // });
          window.location.href = `${res.Data.MpUrl}`;
        },
      },
    });
  };
  reload = () => {
    const { dispatch } = this.props;
    this.setState({reloadLoading:true})
    dispatch({
      type: 'xcxauth/GetWxaCode',
      callback: {
        success: res => {
          this.setState({
            wxaCode:res.Data.ImgUrl,
            reloadLoading:false
          })
          message.success('刷新成功');
        },
        error: res => {
          this.setState({reloadLoading:false})
          message.error('刷新失败：'+res.Msg);
        }
      }
    });
  };
  showAuthModal = () => {
    this.setState({reauthorizeVisible:true})
  };
  delCXAppid = (WxaId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'xcxauth/delXCXAppid',
      payload: {
        WxaId: WxaId,
      },
      callback: {
        success: res => {
          if(res.Code===0){
            message.success('删除成功');
            this.setState({lookVisible:false})
            this.getAuthInfo()
          }else{
            message.error('删除失败：'+res.Msg);
          }
        }
      }
    });
  }
  addXCX = () =>{
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      dispatch({
        type: 'xcxauth/addXCXAppid',
        payload: {
          WxaId: values.WxaId,
          Remark: values.Remark?values.Remark:'',
        },
        callback: {
          success: res => {
            if(res.Code===0){
              message.success('添加成功');
              this.setState({addVisible:false})
              this.getAuthInfo()
              form.setFieldsValue({'WxaId':'','Remark':''})
            }else{
              message.error('添加失败：'+res.Msg);
            }
          }
        }
      });
    })
  }
  getAppIdList = ()=> {
    const { dispatch } = this.props;
    this.setState({lookVisible:true});
    dispatch({
      type: 'xcxauth/GetAppIdList',
      callback: {
        success: res => {
          if(res.Code===0){
            this.setState({appIdList:res.Data})
          }
        }
      }

    });
  }
  inputBZ = (event)=>{
    const v=event.target.value
    if(v.length>12){
      return
    }
    this.setState({bzLength:v.length})
  }
  resetAddModal = ()=>{
    const { form } = this.props;
    this.setState({addVisible:false,bzLength:0});
    form.setFieldsValue({'WxaId':'','Remark':''})
  }
  showXcxCodeModal= ()=>{
    this.setState({xcxCodeModal:true});
  }
  render() {
    const {
      authInfo,
      authInfo: { Permission: authList },
      cdnUrl,
      authStatus,
      match,
      loadingTable,
      form: { getFieldDecorator },
      appIdList,
      loadingAid,
      addLoading
    } = this.props;
    const { loading, code, bzLength, wxaCode,reloadLoading}=this.state;

    //const {authList:{Permission}} =authInfo;
    //console.log(wxaCode)
    const newlist=jiequ(authList,2);
    const dataSource = [{
      key:'1',
      tit: '小程序名称',
      essinfo: authInfo.AppName || '-',
      explain: '小程序发布后，非个人帐户可通过认证方式改名。',
      act:'重新授权',
      },{
        key:'2',
        tit: '小程序ID',
        essinfo: authInfo.AppId || '-',
        explain: '每个小程序ID特有的ID号',
        act:'',
      },
      {
        key:'3',
        tit: '小程序码',
        essinfo: wxaCode,
        explain: '只可访问线上版本小程序',//<QRCode size={124} value={qrurl}/>
        act:'刷新',
      },{
        key:'4',
        tit: '小程序介绍',
        essinfo: authInfo.Signature || '-',
        explain: '一个月内可申请5次修改',
        act:'',
      },{
        key:'5',
        tit: '服务范围',
        essinfo: authInfo.CatesDescr || '-',
        explain: '一个月内可申请修改3次',
        act:'',
      },{
        key:'6',
        tit: '微信认证',
        essinfo: authInfo.VerifyType || '-',
        explain: '已认证帐号可使用微信支付权限，个人类型帐号暂不支持微信认证（认证入口：登录小程序——设置——基本设置——微信认证——详情）',
        act:'',
      },{
        key:'7',
        tit: '版本号',
        essinfo: authInfo.Version || '-',
        explain: '当前线上版本',
        act:'详情',
      },{
        key:'8',
        tit: '目标小程序',
        essinfo: authInfo.NavigateToMiniProgramAppIdList?authInfo.NavigateToMiniProgramAppIdList+'个':0,
        explain: '目标小程序即在当前小程序里允许跳转去的其他小程序，最多10个；若要修改，则需再次提交版本审核',
        act:['查看','添加'],
    }];
    const columns = [{
      title: '基本信息',
      dataIndex: 'tit',
      colSpan: 2,
      width: '17%',
      align: 'left',
    }, {
      title: '',
      dataIndex: 'essinfo',
      colSpan: 0,
      width: '30%',
      render: (text, row, index) => {
        if(index===2){
          return <span>{text?<img onClick={this.showXcxCodeModal} style={{width:44,height:44,cursor:"pointer"}} src={text}/>:'-'}</span>
        }else{
          return <span>{text}</span>
        }
      }
    }, {
      title: '说明',
      dataIndex: 'explain',
      className: 'explain',
    }, {
      title: '操作',
      dataIndex: 'act',
      width: '10%',
      align: 'right',
      render: (text, row, index) => {
        if (index === 7) {
          return <span>
            <a href="javascript:void(0)" onClick={this.getAppIdList} style={{marginRight:'8px'}}>{text[0]}</a>
            <a href="javascript:void(0)" onClick={()=>{this.setState({addVisible:true})}}>{text[1]}</a>
          </span>;
        }else if(index === 0){
          return <a href="javascript:void(0)" onClick={this.showAuthModal}>{text}</a>
        }else if(index===2){
          return (authInfo.Version&&!reloadLoading?
          <a href="javascript:void(0)" style={{display:"inline-block"}} onClick={this.reload}><Spin size="small" spinning={reloadLoading}>{text}</Spin></a>:
          authInfo.Version&&reloadLoading?
          <a href="javascript:void(0)" style={{display:"inline-block"}}><Spin size="small" spinning={reloadLoading}>{text}</Spin></a>:
          null)
        }else if(index===6){
          return <a href="javascript:void(0)" onClick={()=>{router.push(`/${match.params.storeId}/wechat/miniapp/version`);}}>{text}</a>
        }
        return {
          children: <a href="javascript:;">{text}</a>,

        };
      },
    }];
    const xcxColumns = [{
      title: '允许跳转的目标小程序APPID',
      dataIndex: 'AppId',
      align: 'left',
      key: 'AppId'
    },{
      title: '备注',
      dataIndex: 'Remark',
      width: '25%',
      align: 'left',
      key: 'Remark'
    },{
      title: '操作',
      width: '25%',
      align: 'right',
      key: 'delete',
      render: (text, row, index) => {
        // return (<Popconfirm className={styles.zindexPop} style={{zIndex:1051}} placement="topLeft" title="删除后将不能再跳转至该小程序" onConfirm={()=>{this.delCXAppid(row.AppId)}} okText="确认" cancelText="取消">
        //   <a onClick={()=>{this.delCXAppid(row.AppId)}}>删除</a>
        // </Popconfirm>)
        return <a onClick={()=>{this.delCXAppid(row.AppId)}}>删除</a>
      }
    }]
    const formItemLayout1 =  {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    };
    const formItemLayout2 =  {
      labelCol: { offset: 8, span:2 },
      wrapperCol: { span: 14 }
    };
    //备注只能输入12个字符
    const bzValidator = (rule, value, callback) => {
      if (value&&value.length>12) {
        this.props.form.setFieldsValue({'Remark':value.substring(0,12)})
      }
      // 必须总是返回一个 callback，否则 validateFields 无法响应
      callback();
    }

    return (
      <Fragment>
        {
          this.state.isAuth?
          <Spin spinning={loading}>
          <Card title={'基本信息'} className={styles.EssInfo} bordered={false}>
            <Table rowKey="id" loading={loadingTable} columns={columns} dataSource={dataSource} bordered={false} pagination={false} />
          </Card>
          <Card title={'已授权权限'} style={{marginTop:16}} className={styles.AuthList} bordered={false}>
            {newlist && newlist.length
              ? newlist.map((item, index) => {
                  return (
                    <Row style={{marginBottom: 10}} key={index} >
                    {
                      item.map((v,i)=>{
                        return (
                          <Col key={i} span={12}>
                            <Tag
                              style={{
                                color: v.Auth ? '#52C41A' : '#BFBFBF',
                                border: v.Auth ? '1px solid #52C41A' : '1px solid #BFBFBF',
                              }}
                            >
                              {v.Auth ? '已授权' : '未授权'}
                            </Tag>
                            <span>{v.Name}</span>
                          </Col>
                        )
                      })
                    }
                    </Row>
                  );
                })
              : null}
          </Card>
          </Spin>
          :
          <Fragment>
            <Row gutter={16}>
              <Col span={12}>
                <div className={styles.Unauthorized}>
                  <div><img src={cdnUrl + '/' + 'xkdnewyun/systemfile/store/icon/weapp_hasxcx.png'}/></div>
                  <div className={styles.textBlod}>我已拥有微信小程序</div>
                  <div className={styles.textSmall}>小程序管理员可一键将小程序授权绑定到店铺</div>
                  <Button type="primary" onClick={() => this.goAuth()}>一键授权绑定小程序</Button>
                </div>
              </Col>
              <Col span={12}>
                <div className={styles.Unauthorized}>
                  <div><img src={cdnUrl + '/' + 'xkdnewyun/systemfile/store/icon/weapp_noxcx.png'}/></div>
                  <div className={styles.textBlod}>还没有微信小程序</div>
                  <div className={styles.textSmall}>如有认证服务号，可从公众号后台创建免去认证流程</div>
                  <Button onClick={() => window.open('https://mp.weixin.qq.com')}>去微信公众平台申请</Button>
                </div>
              </Col>
            </Row>
            <Card title={'温馨提示'} style={{marginTop:24}} className={styles.Prompt}>
              <div>1. 一个小程序账号只能和一个店铺绑定；</div>
              <div>2. 为保证店铺功能正常使用，授权时请保持默认选择，勾选所有权限；</div>
              <div>3. 确认要绑定的小程序账号没有授权给其他系统使用。</div>
              {code===50002?<div>4. 店铺已关联微信认证主体：<span>{authStatus.PrincipalName}</span>。要绑定的小程序必须与当前主体一致。</div>
              :<div>4. 推荐使用企业主体的账号绑定，首次绑定后，主体信息会关联到店铺，且不能更换，请提前确定您要使用的主体。</div>}
            </Card>
          </Fragment>
        }
        <Modal
          title="提示"
          visible={this.state.reauthorizeVisible}
          onOk={this.goAuth}
          onCancel={() => {this.setState({reauthorizeVisible:false})}}
        >
          <p> 1、重新授权时不可换绑其他微信小程序，否则重新授权将失败；</p>
          <p>2、为保证系统功能的正常使用，授权时请保持默认选择，把开放平台账号管理权限统一授权给本系统。</p>
        </Modal>
        <Modal
          title="小程序码"
          visible={this.state.xcxCodeModal}
          onCancel={() => {this.setState({xcxCodeModal:false})}}
          footer={null}
          width={320}
        >
          <div style={{textAlign:"center"}}><img style={{width:200,height:200}} src={wxaCode}/></div>
        </Modal>
        <Modal
          title="允许跳转的目标小程序"
          visible={this.state.lookVisible}
          onCancel={() => {this.setState({lookVisible:false})}}
          footer={null}
        >
          <Table loading={loadingAid} columns={xcxColumns} dataSource={appIdList} bordered={false} pagination={false} />
        </Modal>
        <Modal
          title="添加小程序"
          visible={this.state.addVisible}
          onOk={this.addXCX}
          onCancel={this.resetAddModal}
          okButtonProps={{loading:addLoading}}
        >
          <div style={{marginBottom:'24px'}}>注意：修改跳转的appid需要重新提交版本审核</div>
          <Form layout='horizontal'>
            <Form.Item
            label="跳转目标小程序Appid"
            {...formItemLayout1}
            >
              {getFieldDecorator('WxaId', {
                rules: [{
                  required: true,
                  message:'请输入小程序appid'
                }],
          })(
                <Input/>
              )}
            </Form.Item>
            <Form.Item
            label="备注"
            {...formItemLayout2}
            >
              {getFieldDecorator('Remark', {
                rules: [{
                  validator:bzValidator,
                }],
          })(
                <Input onChange={this.inputBZ} suffix={<span style={{color:'#BFBFBF'}}>{`${bzLength}/12`}</span>}/>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </Fragment>
    );
  }
}

export default connect(({ xcxauth, global,loading }) => ({
  cdnUrl:global.oemInfo.cdnUrl,
  authStatus:xcxauth.authStatus,
  loadingTable: loading.effects['xcxauth/GetAuthInfo'],
  appIdList:xcxauth.appIdList,
  loadingAid: loading.effects['xcxauth/GetAppIdList'],
  addLoading: loading.effects['xcxauth/addXCXAppid'],
}))(AuthSuccess);
